# -*- coding: utf-8 -*-

import os

from gi.repository import Gtk
from gi.repository import BraseroBurn
from gi.repository import BraseroMedia

class ToquinCDException(Exception):
	message = None
	
	def __init__(self, message):
		self.message = message

	def __str__(self):
		return self.message

class ToquinBurner(Gtk.Dialog):
	signal_id = None
	toquin_model = None
	progress_bar = None
	
	def __init__(self, toquin_model, title=None, parent=None, flags=0, buttons=None):
		Gtk.Dialog.__init__(self, title, parent, flags, buttons)
		self.toquin_model = toquin_model

		information_label = Gtk.Label()
		information_label.set_text("Progreso:")
		self.get_content_area().pack_start(information_label)
		
		self.progress_bar = Gtk.ProgressBar()
		self.get_content_area().pack_start(self.progress_bar)

		self.get_content_area().show_all()
		self.set_modal(True)
		
	def burn_installables(self):
		BraseroBurn.start()

		# Config
		monitor = BraseroMedia.MediumMonitor()
		all_drives = monitor.get_drives(BraseroMedia.TYPE_ALL)
		burner = filter(lambda x : not x.is_fake() and x.get_device() == "/dev/sr0", all_drives)[0]

		session = BraseroBurn.SessionCfg()
		session.set_burner(burner)

		# Config
		file_root = ""
		grafts = []
		
		for item in self.toquin_model.getMarkedForInstallation():
			item_path = os.path.join(file_root, item.filename)
			grafts.append(BraseroBurn.GraftPoint("file://%s" % item_path, "Toquin/%s" % os.path.basename(item.filename)))
			print "Appending %s" % item_path

		track = BraseroBurn.TrackDataCfg()
		track.set_source(grafts, None)

		session.add_track(track, None)

		self.signal_id  = session.connect('is-valid', self.burn_installables_ready, session)
		
		return self.run()
		
	def burn_installables_ready(self, sender, session):
		if session.get_error() == 0:
			sender.disconnect(self.signal_id)

			burn = BraseroBurn.Burn()
			burn.connect('progress-changed', self.report_progress)
			burn.record(session)

			self.response(0)

	def report_progress(self, sender, overall_progress, task_progress, remaining):
		self.progress_bar.set_fraction(overall_progress)
